<?php

namespace Admin\Help;

//缓存使用通用方法
use Admin\AppConst\WebConst;

class Cache
{
    public $redis;

    function __construct()
    {
        $this->redis = New \Redis();
        $host = C('REDIS_HOST');
        $post = C('REDIS_PORT');
        $auth = C('REDIS_AUTH');
        $status = $this->redis->connect($host, $post);
        if (!empty($status)) {
            $this->redis->auth($auth);
        } else {
            $this->redis = false;
        }
    }

    /**
     * 使用0号库读取缓存,默认有前缀
     */
    static function get($key)
    {

        $redis = new \Think\Cache\Driver\Redis();
        $data = $redis->get($key);
        if (false === $data) {
            return false;
        } elseif (empty($data)) {
            return $data;
        } else {
            return $data;
        }
    }

    /**
     * 使用0号库设置redis值,默认有前缀
     */
    static function set($key, $value, $time)
    {
        //读取缓存
        $redis = new \Think\Cache\Driver\Redis();
        $data = $redis->set($key, $value, $time);
    }

    /*
     * 设置值
     */
    function setp($key, $value, $time, $table = 100)
    {
        if (false == $this->redis) {
            return false;
        }
        $this->redis->select($table);
        return $this->redis->set($key, $value, $time);
    }

    /*
     * 获取值
     */
    function getp($key, $table = 100)
    {
        if (false == $this->redis) {
            return false;
        }
        $this->redis->select($table);
        $data = $this->redis->get($key);
        if (false === $data) {
            return false;
        } else {
            return $data;
        }
    }

    /*
     * 增量
     * 错误返回false,成功返回重新计算后的值
     */
    function incrby($key, $add, $table = 100)
    {
        if (false == $this->redis) {
            return false;
        }
        $this->redis->select($table);
        $data = $this->redis->get($key);
        if (empty($data)) {
            return false;
        } else {
            @ $new = $this->redis->incrByFloat($key, $add);
            return $new;
        }
    }

    /**
     * 使用list来存多条数据
     */
    function lpush($key, $value, $table = 100)
    {
        if (false == $this->redis) {
            return false;
        }
        $this->redis->select($table);
        return $this->redis->lpush($key, $value);
    }
}
